<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <div class="max-w-4xl mx-auto">
      <h1 class="text-3xl font-bold text-gray-800 mb-6">父应用控制面板</h1>

      <!-- 连接状态 -->
      <div class="mb-6">
        <div class="flex items-center">
          <div class="w-3 h-3 rounded-full mr-2" :class="{
            'bg-green-500': messenger.state.isConnected,
            'bg-gray-500': !messenger.state.isConnected
          }"></div>
          <span v-if="messenger.state.isConnected" class="text-green-600">已连接</span>
          <span v-else class="text-gray-600">未连接</span>
          <span class="text-sm text-gray-500 ml-4">
            消息: {{ messenger.state.messageCount }} 条
          </span>
          <span class="text-sm text-gray-500 ml-4">
            最后消息: {{ formatTime(messenger.state.lastMessageTime) }}
          </span>
        </div>
      </div>

      <!-- iframe容器 -->
      <div class="bg-white rounded-lg shadow p-6 mb-6">
        <h2 class="text-xl font-semibold text-gray-700 mb-4">子应用</h2>
        <iframe ref="childFrame" src="/child.html" class="w-full h-96 border border-gray-300 rounded"
          @load="onIframeLoad"></iframe>
      </div>

      <!-- 消息输入 -->
      <div class="bg-white rounded-lg shadow p-6 mb-6">
        <h2 class="text-xl font-semibold text-gray-700 mb-4">发送消息给子应用</h2>
        <div class="flex">
          <input v-model="parentMessage" type="text" placeholder="输入消息..."
            class="flex-1 px-4 py-2 border border-gray-300 rounded-l focus:outline-none focus:ring-2 focus:ring-blue-500">
          <button @click="sendToChild"
            class="px-4 py-2 bg-blue-500 text-white rounded-r hover:bg-blue-600 focus:outline-none">发送</button>
        </div>

        <!-- 主题设置 -->
        <div class="mt-4">
          <h3 class="text-lg font-medium text-gray-700 mb-2">设置子应用主题</h3>
          <div class="flex flex-wrap gap-2">
            <button v-for="theme in themes" :key="theme.color" @click="setChildTheme(theme)" :class="theme.class"
              class="px-3 py-1.5 rounded transition-colors">
              {{ theme.name }}
            </button>
          </div>
        </div>
      </div>

      <!-- 消息历史 -->
      <div class="bg-white rounded-lg shadow p-6 mb-6">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-semibold text-gray-700">消息历史</h2>
          <button @click="messageHistory = []" class="text-sm text-red-500 hover:text-red-700">清空</button>
        </div>
        <div class="border border-gray-200 rounded h-64 overflow-y-auto p-4 bg-gray-50">
          <div v-for="(msg, index) in messageHistory" :key="index" class="mb-2">
            <div class="text-xs text-gray-500">{{ msg.timestamp }}</div>
            <div class="text-gray-800">{{ msg.text }}</div>
          </div>
          <div v-if="messageHistory.length === 0" class="text-gray-500 text-center py-8">
            暂无消息
          </div>
        </div>
      </div>

      <!-- 开发者工具 -->
      <div class="bg-white rounded-lg shadow p-6 mb-6">
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-semibold text-gray-700">开发者工具</h2>
          <button @click="toggleDevTools" class="text-sm text-gray-500 hover:text-gray-700">
            {{ showDevTools ? '隐藏' : '显示' }}
          </button>
        </div>

        <div v-if="showDevTools">
          <h3 class="text-lg font-medium text-gray-700 mb-2">示例消息</h3>
          <div class="flex flex-wrap gap-2 mb-4">
            <button v-for="(msg, index) in sampleMessages" :key="index" @click="sendSampleMessage(msg)"
              class="px-3 py-1.5 bg-gray-100 text-gray-700 rounded hover:bg-gray-200">
              {{ msg.type }}: {{ msg.payload || '无内容' }}
            </button>
          </div>

          <div class="border-t border-gray-200 pt-4">
            <button @click="messenger.requestHelp('UI渲染问题')"
              class="px-3 py-1.5 bg-yellow-100 text-yellow-800 rounded hover:bg-yellow-200">
              模拟请求帮助
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useIframeMessenger, MessageType } from '~/composables/useIframeMessenger'

definePageMeta({
  layout: 'minimal',
  showHeader: false
});
// 主题选项
const themes = [
  { name: '默认', class: 'bg-gray-100 text-gray-800 hover:bg-gray-200', color: 'gray' },
  { name: '蓝色', class: 'bg-blue-100 text-blue-800 hover:bg-blue-200', color: 'blue' },
  { name: '绿色', class: 'bg-green-100 text-green-800 hover:bg-green-200', color: 'green' },
  { name: '红色', class: 'bg-red-100 text-red-800 hover:bg-red-200', color: 'red' },
  { name: '紫色', class: 'bg-purple-100 text-purple-800 hover:bg-purple-200', color: 'purple' },
]

// DOM 元素引用
const childFrame = ref<HTMLIFrameElement | null>(null)
const parentMessage = ref('')
const showDevTools = ref(false)

// 消息历史记录
const messageHistory = ref<Array<{ text: string, timestamp: string }>>([])

// 初始化通信管理器
const messenger = useIframeMessenger(childFrame)

// 添加消息处理器
messenger.onMessage(MessageType.CHILD_MESSAGE, (payload: string) => {
  addMessage(`子应用: ${payload}`)
})

messenger.onMessage(MessageType.REQUEST_HELP, (payload: string) => {
  addMessage(`⚠️ 子应用请求帮助: ${payload}`)
})

// 注册可被调用的函数
onMounted(() => {
  // 注册一个简单函数
  messenger.registerFunction('getUserInfo', () => {
    return {
      name: '张三',
      age: 30,
      email: 'zhangsan@example.com'
    };
  });

  // 注册一个异步函数
  messenger.registerFunction('calculate', async (a: number, b: number) => {
    // 模拟异步操作
    await new Promise(resolve => setTimeout(resolve, 1000));
    return a + b;
  });

  // 注册一个带复杂逻辑的函数
  messenger.registerFunction('getWeather', (city: string) => {
    const weatherData: Record<string, string> = {
      '北京': '晴, 25°C',
      '上海': '多云, 28°C',
      '广州': '小雨, 30°C',
      '深圳': '雷阵雨, 29°C'
    };

    return weatherData[city] || '未知城市';
  });

  // 注册一个可能会出错的函数
  messenger.registerFunction('divide', (a: number, b: number) => {
    if (b === 0) throw new Error('除数不能为零');
    return a / b;
  });
});

// iframe加载完成处理
const onIframeLoad = () => {
  console.log('子应用 iframe 加载完成')
  setTimeout(() => {
    messenger.sendMessage(MessageType.INIT, '父应用已准备好!')
  }, 500)
}

// 组件卸载时清理
onBeforeUnmount(() => {
  messenger.unregisterFunction('getUserInfo');
  messenger.unregisterFunction('calculate');
  messenger.unregisterFunction('getWeather');
  messenger.unregisterFunction('divide');
});

// 发送消息给子应用
const sendToChild = () => {
  if (!parentMessage.value.trim()) return

  messenger.sendMessage(MessageType.PARENT_MESSAGE, parentMessage.value)
  addMessage(`父应用: ${parentMessage.value}`)
  parentMessage.value = ''
}

// 设置子应用主题
const setChildTheme = (theme: typeof themes[0]) => {
  messenger.setTheme(theme.color)
  addMessage(`设置主题: ${theme.name}`)
}

// 添加消息到历史记录
const addMessage = (text: string) => {
  const now = new Date()
  const timestamp = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`

  messageHistory.value.unshift({
    text,
    timestamp
  })

  // 最多保留20条记录
  if (messageHistory.value.length > 20) {
    messageHistory.value.pop()
  }
}

// 格式化时间
const formatTime = (date: Date | null) => {
  if (!date) return '--:--:--'
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`
}

// 切换开发者工具
const toggleDevTools = () => {
  showDevTools.value = !showDevTools.value
}

// 示例消息
const sampleMessages = [
  { type: MessageType.PARENT_MESSAGE, payload: '你好，子应用!' },
  { type: MessageType.PARENT_MESSAGE, payload: '这是一个测试消息' },
  { type: MessageType.SET_THEME, payload: 'blue' },
  { type: MessageType.REQUEST_HELP, payload: 'UI渲染问题' }
]

// 发送示例消息
const sendSampleMessage = (msg: any) => {
  messenger.sendMessage(msg.type as any, msg.payload)
  addMessage(`调试消息: ${msg.type.toString()}: ${msg.payload || '无内容'}`)
}
</script>

<style scoped>
/* 样式保持不变 */
</style>